package com.example.smart.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.config.JwtHelper;
import com.example.smart.handler.HutoolPasswordEncoder;
import com.example.smart.mapper.AdminMapper;
import com.example.smart.pojo.Admin;
import com.example.smart.security.AccountAdmin;
import com.example.smart.security.SysUserDetailService;
import com.example.smart.service.AdminService;
import com.example.smart.util.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl< AdminMapper, Admin > implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    /*@Autowired
    private AuthenticationManager authenticationManager;*/
    @Autowired
    private HutoolPasswordEncoder passwordEncoder;
    @Autowired
    private SysUserDetailService sysUserDetailService;
    @Autowired
    private RedisCache redisCache;

    // 管理员名称正则达式
    private static final String USERNAME_REGEX = "^[a-zA-Z0-9_-]{4,16}$";
    // 邮箱正则达式
    private static final String EMAIL_REGEX = "\\w+@(\\w+\\.)+\\w+";
    // 手机号正则达式
    private static final String PHONE_REGEX = "^1[3456789]\\d{9}$";
    private Boolean isAdminName(String str) {
        if (str == null) {
            return false;
        }
        return str.matches(USERNAME_REGEX);
    }

    public Boolean isPhoneNumber(String str) {
        if (str == null) {
            return false;
        }
        return str.matches(PHONE_REGEX);
    }

    private Boolean isEmail(String str) {
        if (str == null) {
            return false;
        }
        return str.matches(EMAIL_REGEX);
    }

    @Override
    public Map< String, Object > login(Admin admins) {
        Map< String, Object > map = new HashMap<>();
        QueryWrapper< Admin > queryWrapper = new QueryWrapper<>();
        String adminName = admins.getAdminName();
        String adminEmail = admins.getAdminEmail();
        String adminPhone = admins.getAdminPhone();

        Boolean isAdminName = isAdminName(adminName);
        Boolean isPhone = isPhoneNumber(adminPhone);
        Boolean isEmail = isEmail(adminEmail);
        //查询条件，通过管理员名称来查找管理员
        if (isAdminName) {
            queryWrapper.eq("admin_name", adminName);
        } else if (isPhone) {
            queryWrapper.eq("admin_phone", adminPhone);
        } else if (isEmail) {
            queryWrapper.eq("admin_email", adminEmail);
        }
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin == null) {
            map.put("state", "nource");
        } else {
            //密码比对就应该是前端传递的明文密码+盐最后MD5加密和数据库加密密码比对后再跟数据库密码比对
            if (admin.getPassword().equals(SecureUtil.md5(admins.getPassword() + admin.getAdminSalt()))) {
                String token;
               /* UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(admin.getAdminName(), admin.getPassword());
                Authentication authentication = authenticationManager.authenticate(authenticationToken);
                AccountAdmin accountAdmin = (AccountAdmin) authentication.getPrincipal();*/
                AccountAdmin accountAdmin = (AccountAdmin) sysUserDetailService.loadUserByUsername(admin.getAdminName());
                Integer adminId = accountAdmin.getAdmin().getAdminId();
                //生成token
                if (isAdminName) {
                    token = JwtHelper.getToken(adminId, adminName, "admin");
                } else if (isPhone) {
                    token = JwtHelper.getToken(adminId, adminPhone, "admin");
                } else if (isEmail) {
                    token = JwtHelper.getToken(adminId, adminEmail, "admin");
                } else {
                    return map;
                }
                map.put("token", token);
                map.put("state", "success");
                redisCache.setCacheObject("admin_token:" + adminId, accountAdmin);
            } else {
                map.put("state", "error");
            }
        }
        return map;
    }
}
